var toolUtil = require('../common/utils/toolUtil');
var messageUtil = require('../common/utils/messageUtil');
var moment = require('moment');

/**
 * To check the request token
 */
exports.doCheckToken = function (req, res, next) {

    var tempArray = req.url.split('/');
    var token = req.query.token ? req.query.token : tempArray[tempArray.length - 2];

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            res.json(messageUtil.composeErrorMessage(req, ErrorMessage.LOGON_EXPIRED, 1000))
        } else {
            req.user = user;

            /* 宝宝树66小区三期改造 新版本成功上线后,旧版本提示下载新版本 add wangcan 20171012 start */
            if (token != null) {
                var sysDate = Date.now(); // 当前系统时间毫秒值
                logger.debug('newAppVersionPublicDate:' + newAppVersionPublicDate);
                logger.debug('updateMsgPushDate:' + updateMsgPushDate);
                // 新版本APP发布时间
                var appPublicDate = moment(newAppVersionPublicDate, "YYYY-MM-DD").format();
                // 版本更新提示开始时间
                var updateInfoPushDate = moment(updateMsgPushDate, "YYYY-MM-DD").format();
                appPublicDate = new Date(appPublicDate).getTime();
                updateInfoPushDate = new Date(updateInfoPushDate).getTime();
                if (sysDate >= updateInfoPushDate && sysDate < appPublicDate) {
                    logger.debug('引导用户下载新版APP start...');

                    var userId = user._id;
                    var date = moment().format('YYYYMMDD');
                    var type = req.query.type; // android或ios
                    // var vcode = req.query.vcode; // 版本号100000
                    var vname = req.query.vname; // 版本号1.0.0
                    // 最新版版本号100000
                    if(vname && vname != '1.0.0') {
                        var redisKey = "guide_user_download_new_app:date:" + date + ":userId:" + userId;
                        logger.debug('引导用户下载新版APP redisKey...' + redisKey);
                        redisClient.incr(redisKey, function(err, reply) {
                            redisClient.get(redisKey, function(errInner, replyInner) {
                                logger.debug(redisKey + '...' + replyInner);
                                if(replyInner && replyInner == 1) {
                                    logger.debug('引导用户下载新版APP real start...');
                                    var desc = '你好，66小区有新版喽~快去应用市场搜索“宝宝树66小区”，下载最新V1.0.0版本吧~\n（旧版本11月起将无法使用）';
                                    restClient.get("http://66xiaoqu.babytreeimg.com/app/json/download_1023.json", function (data, response) {
                                        if (type == 'android') {
                                            url = data.android.default;
                                        } else {
                                            url = data.android.default;
                                        }
                                        logger.debug('getDownloadNewAppUrl...' + url);
                                        var params = {msgType: 'guide_user_download_new_app', uid: userId, desc: desc, date: date, url: url};
                                        toolUtil.putMessageBusinessMQ(params);
                                    }).on('error', function (err) {
                                        logger.error('getDownloadNewAppUrl fail...' + err.message);
                                        var params = {msgType: 'guide_user_download_new_app', uid: userId, desc: desc, date: date, url: url};
                                        toolUtil.putMessageBusinessMQ(params);
                                    });
                                }
                            });
                            redisClient.expire(redisKey, 86400);
                        });
                    }
                }
            }
            /* 宝宝树66小区三期改造 新版本成功上线后,旧版本提示下载新版本 add wangcan 20171012 end */
            next();
        }
    });
};